package com.mlm.mlmapp.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.Adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.util.Constants;
import com.mlm.mlmapp.R;
import com.mlm.mlmapp.activity.layoutmanager.SyGridLayoutManager;
import com.mlm.mlmapp.adapter.view.GridMarginDecoration;
import com.mlm.mlmapp.adapter.view.listener.DresserClickListener;
import com.mlm.mlmapp.adapter.view.listener.OnNextPageShouldDownloadListener;
import com.mlm.mlmapp.adapter.view.listener.OnRcvScrollListener;
import com.mlm.mlmapp.animation.RecyclAnimation;
import com.mlm.mlmapp.cons.HTTPCons;
import com.mlm.mlmapp.interfaces.Prefs_;
import com.mlm.mlmapp.utils.CommonUtils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.DimensionRes;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

@EActivity(R.layout.my_comments_list)
public class MyCommentsListActivity extends BaseActivity implements HTTPCons,
		DresserClickListener {
	public static final int REQUEST_CODE = 11;
	public static final int DESC = 1;
	public static final int ASC = 2;
	public static final int NORMAL = 0;
	@DimensionRes(R.dimen.recyclerview_sylist_space)
	float commentImagesMargin;
	int mPage=1;
	@DimensionRes
	float comments_images_edge;
	@ViewById
	TextView tv_no_title;
	@Extra
	String orderid;
	private AQuery aq;
	private MyCommentsListAdapter adapter;
	List<JSONObject> myCommentsListDataset;
	private AjaxCallback<JSONArray> commentsCB;
	@ViewById
	RecyclerView rv_comments;
	@DimensionRes(R.dimen.recyclerview_mycomments_space)
	float recyclerview_mycomments_space;
	@Pref
	Prefs_ myPrefs;

	@AfterViews
	public void init() {
		String title=getTitle().toString();
		if(!"".equals(title)){
			((TextView) this.findViewById(R.id.tv_title)).setText(title);
		}
		
		aq = new AQuery(this);
		aq.hardwareAccelerated11();
		if (orderid == null) {
			orderid = "";
		}
		commentsCB = new AjaxCallback<JSONArray>() {

			@Override
			public void callback(String url, JSONArray object, AjaxStatus status) {
				// TODO Auto-generated method stub
				super.callback(url, object, status);
				if(status.getCode()==-101){
					Toast.makeText(aq.getContext(), "网络异常,请检查网络", Toast.LENGTH_SHORT);
					return;
				}

					for (int i = 0; i < object.length(); i++) {
						try {
							myCommentsListDataset.add(object.getJSONObject(i));
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				if (myCommentsListDataset.size() > 0) {
					rv_comments.setVisibility(View.VISIBLE);
				} else {
					rv_comments.setVisibility(View.INVISIBLE);
				}

				adapter.notifyDataSetChanged();
				mPage++;
			}

		};
		myCommentsListDataset = new ArrayList<>();
		ImageView iv = (ImageView)findViewById(R.id.iv_default);
		TextView t = (TextView) findViewById(R.id.tv_content);
		iv.setImageResource(R.drawable.noitem_comment);
		t.setText("暂无评价信息");
		final GridLayoutManager layoutManager = new SyGridLayoutManager(this, 1);
		rv_comments.setLayoutManager(layoutManager);

		rv_comments.addItemDecoration(new GridMarginDecoration(this, 0, 0, 0,
				recyclerview_mycomments_space));
		rv_comments.setItemAnimator(new RecyclAnimation());
		adapter = new MyCommentsListAdapter(MyCommentsListActivity.this,
				myCommentsListDataset);
		OnRcvScrollListener listener = new OnRcvScrollListener() {

			@Override
			public void onBottom() {
				// TODO Auto-generated method stub
				super.onBottom();
				updateDataset(mPage);
			}

		};
		rv_comments.setOnScrollListener(listener);

		rv_comments.setAdapter(adapter);
		// init sylist date
		updateDataset(mPage);
	}

	@OnActivityResult(REQUEST_CODE)
	void onResult(Intent data) {
		if (data != null) {

		}
	}

	@Click
	void btn_dresser_type() {
		HairDresserFilterActivity_.intent(this).startForResult(REQUEST_CODE);
	}

	// values bought starLevel levlId studioId
	void updateDataset(int page) {
		StringBuilder url = new StringBuilder(get_user_comments_action);
		getCommentsList(url.toString(), page);

	}

	void getCommentsList(String url, int page) {
		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		 pairs.add(new BasicNameValuePair("mobile", myPrefs.loginID().get()));
//		pairs.add(new BasicNameValuePair("mobile", "18245189375"));
		pairs.add(new BasicNameValuePair("page", page + ""));
		pairs.add(new BasicNameValuePair("orderId", orderid));
		CommonUtils.postRequest4Array(url, aq, commentsCB, pairs);
	}

	class MyCommentsListAdapter extends
			Adapter<MyCommentsListAdapter.MyCommentsViewHolder> {
		private Context mContext;
		private DresserClickListener mOnCommentsClickListener;
		private List<JSONObject> array;

		public MyCommentsListAdapter(Context con, List<JSONObject> array) {
			this.mContext = con;
			this.mOnCommentsClickListener = (DresserClickListener) con;
			this.array = array;

		}

		@Override
		public int getItemCount() {
			return array.size();
		}

		@Override
		public MyCommentsViewHolder onCreateViewHolder(ViewGroup parent,
				int arg1) {

			MyCommentsViewHolder holder = null;
			if (array.size() == 1 && array.get(arg1) == null) {

				final View view = LayoutInflater.from(mContext).inflate(
						R.layout.noitem, parent, false);
				ImageView iv = (ImageView) view.findViewById(R.id.iv_default);
				TextView t = (TextView) view.findViewById(R.id.tv_content);
				iv.setImageResource(R.drawable.noitem_comment);
				t.setText("暂无评价信息");
				holder = new MyCommentsViewHolder(view);
				holder.itemView.setTag(com.mlm.mlmapp.cons.Constants.IS_EMPTY);

			} else {
				final View view =LayoutInflater.from(mContext).inflate(
						R.layout.my_commnets_list_item, parent, false);
				holder = new MyCommentsViewHolder(view);
			}
			return holder;



//			// TODO Auto-generated method stub
//			MyCommentsViewHolder holder;
//			holder = new MyCommentsViewHolder(LayoutInflater.from(
//					MyCommentsListActivity.this).inflate(
//					R.layout.my_commnets_list_item, parent, false));
//			return holder;

		}

		/*
		 * { "userComment": { "content": "1", 内容 "starLevel": 1, 星级 "photos": [
		 * 评价图片 { "photoUrl": "20160104140508347785.png", 图片地址 "type": 4,
		 * "linkId": 16, "id": 32 } ] }, "stylistInfo": { 设计师信息 "id": 1, "name":
		 * "设计师", 设计师名称 "leveName": "设计总监", 设计师职位 "introduce": "简介设计师简介", 设计师简介
		 * "iconPhotoUrl": "http://121.40.92.117:9999/1234touxiang.png" 设计师头像 }
		 * }
		 */
		@Override
		public void onBindViewHolder(MyCommentsViewHolder holder, int position) {
			// TODO Auto-generated method stub
			if (holder.itemView.getTag() != null) {
				if ((boolean) holder.itemView.getTag())
					return;
			}
			if (array.size() <= 0) {
				return;
			}
			
			JSONObject obj = array.get(position);
			
			JSONObject commentJson = getJsonObject(obj, "userComment");
			JSONObject dresserInfoJson = getJsonObject(obj, "stylistInfo");
			MyCommentsViewHolder hHolder = holder;
			hHolder.tv_name.setText(getJsonString(dresserInfoJson, "name"));
			hHolder.tv_post.setText(getJsonString(dresserInfoJson, "leveName"));
			hHolder.tv_words
					.setText(getJsonString(dresserInfoJson, "introduce"));
			aq.id(hHolder.iv_headimg).image(
					getJsonString(dresserInfoJson, "iconPhotoUrl"), true, true,
					200, 0, null, Constants.FADE_IN);
			hHolder.id = getJsonString(dresserInfoJson, "id");
//			hHolder.rate.setRating(getJsonInt(commentJson, "starLevel"));
			hHolder.tv_comment_text.setText(getJsonString(commentJson,
					"content"));

			JSONArray imagesArray = getJsonArray(commentJson, "photos");
			if (imagesArray.length() > 0) {
				hHolder.imagesLinear.setVisibility(View.VISIBLE);
				hHolder.imagesLinear.removeAllViews();
				try {
					for (int i = 0; i < imagesArray.length(); i++) {

						String url = imagesArray.getJSONObject(i).getString(
								"photoUrl");
						ImageView iv = new ImageView(
								MyCommentsListActivity.this);

						LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
								(int) comments_images_edge,
								(int) comments_images_edge);

						lp.setMargins((int) commentImagesMargin, 0,
								(int) commentImagesMargin, 0);
						iv.setLayoutParams(lp);
						iv.setMaxHeight((int) comments_images_edge);
						iv.setMaxWidth((int) comments_images_edge);
						aq.id(iv).image(url, true, true, 200, 0, null,
								Constants.FADE_IN);
						hHolder.imagesLinear.addView(iv);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				hHolder.imagesLinear.setVisibility(View.GONE);
			}
		}



		public class MyCommentsViewHolder extends RecyclerView.ViewHolder {
			String id;
			ImageView iv_headimg;
			Button btn_appointment;
			ImageView photo_one;
			ImageView photo_two;
			ImageView photo_three;
			TextView tv_name;
			TextView tv_post;
			TextView tv_words;
			TextView tv_comment_text;
//			RatingBar rate;
			LinearLayout imagesLinear;

			public MyCommentsViewHolder(View itemView) {
				super(itemView);
				this.tv_name = (TextView) itemView.findViewById(R.id.tv_name);
				this.tv_post = (TextView) itemView.findViewById(R.id.tv_post);
				this.tv_words = (TextView) itemView.findViewById(R.id.tv_words);
				this.tv_comment_text = (TextView) itemView
						.findViewById(R.id.tv_comment_text);
				this.iv_headimg = (ImageView) itemView
						.findViewById(R.id.iv_headimg);
				this.btn_appointment = (Button) itemView
						.findViewById(R.id.btn_appointment);
//				this.rate = (RatingBar) itemView.findViewById(R.id.rate);
				this.imagesLinear = (LinearLayout) itemView
						.findViewById(R.id.ll_images);
				iv_headimg.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						mOnCommentsClickListener.onDresserClick(id);
					}
				});
				this.btn_appointment.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						mOnCommentsClickListener.onAppointmentClick(id);

					}
				});
			}
		}

	}


	@Override
	public void onAppointmentClick(String id) {
		// TODO Auto-generated method stub
		Toast.makeText(this, "预约ID为：" + id + "的设计师", Toast.LENGTH_SHORT);
	}

	@Override
	public void onDresserClick(String id) {
		// TODO Auto-generated method stub
		HairDresserDetailActivity_.intent(MyCommentsListActivity.this)
				.extra("id", id).start();
	}

	@Click
	void btn_back() {
		onBackPressed();
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		Intent data = new Intent();
		setResult(RESULT_CANCELED, data);
		this.finish();
	}
}
